package com.treeroot.treenet.protocol.help;

import com.treeroot.treenet.common.tools.CheckTools;
import com.treeroot.treenet.enums.RequestMethodTypeMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

import static com.treeroot.treenet.common.constant.Constants.*;

/**
 * Create By TreeRoot
 * Create Time: 2023/12/18 03:42
 * Class Name: ExecutePreviousHelp
 * Description:
 * 执行之前的操作
 * @author TreeRoot
 */
public class ExecutePreviousHelp {

    private static final Logger log = LoggerFactory.getLogger(ExecutePreviousHelp.class);

    /**
     * 检查一个标准的HTTP请求
     *
     * @return boolean
     */
    public static boolean checkIsStandardHttp(String requestData) {
        // 检查header是否为空或null
        if (CheckTools.isNullOrEmpty(requestData)) {
            log.error("header may be null or empty");
            return false;
        }
        String standardHead = getStandardHead(requestData);
        // 检查header的三个部分------------------------------------------------------开始
        String[] headSpan = standardHead.split(SPACE);
        if (headSpan.length != 3) {
            log.error("header may not contain three parts,we need Http Protocol");
            return false;
        }
        String requestMethod = headSpan[0];
        if (CheckTools.isNullOrEmpty(RequestMethodTypeMenu.getKeyByValue(requestMethod))) {
            log.error("request method may not be a valid request method");
            return false;
        }
        String requestUrl = headSpan[1];
        byte firstByte = requestUrl.getBytes()[0];
        if (firstByte != ROOT_URL) {
            log.error("request url may not be a valid request url,We need to start with /");
            return false;
        }
        String httpVersion = headSpan[2];
        if (!httpVersion.equals(HTTP_VERSION)) {
            log.error("http version may not be a valid http version,We need to use HTTP/1.1");
            return false;
        }
        // 检查header的个部分------------------------------------------------------结束

        String requestHead = getRequestHead(requestData);
        // 检查请求头的每一行------------------------------------------------------开始
        String[] requestHeadSpan = requestHead.split(ENTER + NEWLINE);
        Map<String, String> headerMap = new HashMap<>();
        for (String s : requestHeadSpan) {
            String[] split = s.split(COLON, 2);
            if (split.length != 2) {
                log.error("request head may not be a valid request head,we need to use key:value");
                return false;
            }
            headerMap.put(split[0], split[1]);
        }
        //检查Host, content-type,user-Agent,accept,accept-encoding,connection,Content-Length是否存在-------开始
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("Host"))) {
            log.error("request head may not be a valid request head,We need to use Host");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("content-type"))) {
            log.error("request head may not be a valid request head,We need to use Content-Type");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("user-Agent"))) {
            log.error("request head may not be a valid request head,We need to use User-Agent");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("accept"))) {
            log.error("request head may not be a valid request head,We need to use Accept");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("accept-encoding"))) {
            log.error("request head may not be a valid request head,We need to use Accept-Encoding");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("connection"))) {
            log.error("request head may not be a valid request head,We need to use Connection");
            return false;
        }
        if (CheckTools.isNullOrEmpty(headerMap.containsKey("Content-Length"))) {
            log.error("request head may not be a valid request head,We need to use Content-Length");
            return false;
        }
        //检查host,User-Agent,Accept,Connection,Content-Length是否存在-------开始

        // 检查请求头的每一行------------------------------------------------------结束


        return true;

    }

    /**
     * 获取标准头
     *
     * @param request 请求
     * @return String
     */

    public static String getStandardHead(String request) {
        String[] lines = request.split(ENTER + NEWLINE);
        if (lines.length > 0) {
            return lines[0];
        } else {
            return "";
        }
    }


    /**
     * 获取请求头
     *
     * @param request 要求
     * @return String
     */


    public static String getRequestHead(String request) {
        //第一个回车换行与第二个回车换行之间的字符串
        int secondIndex = request.indexOf(ENTER + NEWLINE + ENTER + NEWLINE);
        //-1说明没有body
        if (secondIndex == -1) {
            String[] split = request.split(ENTER + NEWLINE);
            //弃掉第一行
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 1; i < split.length; i++) {
                stringBuilder.append(split[i]);
                stringBuilder.append(ENTER + NEWLINE);
            }
            return stringBuilder.toString();
        } else if (secondIndex != -1) {
            //有body,弃掉body,弃掉第一行
            String[] split = request.split(ENTER + NEWLINE + ENTER + NEWLINE);
            String[] header = split[0].split(ENTER + NEWLINE);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 1; i < header.length; i++) {
                stringBuilder.append(header[i]);
                stringBuilder.append(ENTER + NEWLINE);
            }
            return stringBuilder.toString();
        } else {
            log.info("request may not contain header");
            return "";
        }
    }

    /**
     * 获取标准body
     *
     * @param request 要求
     * @return String
     */

    public static String getStandardBody(String request) {
        String[] lines = request.split(NEWLINE + ENTER + NEWLINE);
        if (lines.length > 1) {
            return lines[1];
        } else {
            log.info("request may not contain body");
            return "";
        }
    }

}
